package data.generators;

import java.util.List;

import data.stock.DataHistory;
import data.stock.NewsCorpus;
import data.stock.NewsStory;

/**
 * The NewsReader DataGenerator generates a discretized set of data
 * from a corpus of news, where the summaries are in the format:
 * 
 * METHOD;INFLUENCE;TIME-FRAME
 * 
 * @author Kevin Dolan
 */
public class NewsReader implements DataGenerator {

	private long[] times;
	private String[] methods;
	private double[] influences;
	private long[] timeFrames;
	private long lastNews;
	
	public NewsReader(NewsCorpus corpus) {
		lastNews = corpus.getLastNews();
		
		int count = corpus.getCount();
		
		times = new long[count];
		methods = new String[count];
		influences = new double[count];
		timeFrames = new long[count];
		
		List<NewsStory> news = corpus.getNews();
		int i = 0;
		for(NewsStory story : news) {
			
			long time = story.getTime();
			
			String summary = story.getSummary();
			String[] split = summary.split(";");
			String method = split[0];
			double influence = Double.parseDouble(split[1]);
			int timeFrame = Integer.parseInt(split[2]);
			
			times[i] = time;
			methods[i] = method;
			influences[i] = influence;
			timeFrames[i] = timeFrame;
			
			i++;
		}
	}
	
	@Override
	public DataHistory generate() {
		DataHistory history = new DataHistory();
		double price = 0;
		history.addData(0,0);
		for(long time = 1; time <= lastNews; time++) {
			double effect = 0;
			
			for(int i = 0; times[i] < time; i++) {
				long timeFrame = timeFrames[i];
				if(time - times[i] <= timeFrame) {
					double influence = influences[i];
					if(methods[i].equals("LINEAR")) {
						effect += influence;						
					}
				}
			}
			
			price += effect;
			history.addData(time, price);
		}
		return history;
	}
	
	@Override
	public String getCsv() {
		StringBuffer sb = new StringBuffer();
		sb.append("Time,Method,Influence,Time Frame");
		for(int i = 0; i < times.length; i++) {
			sb.append("\n" + times[i] + "," + methods[i] + "," + influences[i] + "," + timeFrames[i]);
		}
		return sb.toString();
	}
}
